import { generateFileUrlByFileId, generateFileUrl } from './common-methods';
import { cloneDeep } from 'lodash-es';
import { isEmpty } from '@/utils/zmids'

export const appendDateRangeStartEnd = (data, e) => {
  // 查找所有字段，针对特殊Start和End组件进行参数增加
  // 自定义日期类型，需要转换为开始和结束时间
  if (('dateRange' === e.type || 'timeRange' === e.type) && data[e.prop] && data[e.prop].length > 1) {
    data[`${e.prop}Start`] = data[e.prop][0];
    data[`${e.prop}End`] = data[e.prop][1];
    // 后端只能接受一种参数，原始数组删除
    delete data[e.prop];
  }
};

export const appendDateRangeStartEndBack = (data, e) => {
  // 自定义日期类型，数据回填将开始和结束时间转换回来
  if ('dateRange' === e.type || 'timeRange' === e.type) {
    const list = [];
    list.push(data[`${e.prop}Start`]);
    list.push(data[`${e.prop}End`]);
    data[e.prop] = list;
  }
};

// 多选下拉框需要把对应值数组转换为逗号分隔的字符串,同时处理标题映射
export const transSelectVal = (data, e) => {
  const { type, multiple, prop, bindLabel } = e;
  if (type == 'select' && data[prop]) {
    // 多选模式
    if (multiple) {
      data[prop] = data[prop].join(',');
      if (bindLabel && data[`$${prop}`]) {
        data[bindLabel] = data[`$${prop}`].replaceAll('|', ',').replaceAll(' ', '');
      }
    } else {
      if (bindLabel && data[`$${prop}`]) {
        data[bindLabel] = data[`$${prop}`];
      }
    }
  }
};

// 附件组件需要对应多个字段进行赋值
export const transUploadVal = (data, e) => {
  const { type, prop, bindAttrs } = e;
  if (type == 'upload' && data[prop]) {
    const files = cloneDeep(data[prop]);

    let uploadValue = 'fileId';
    if (bindAttrs && bindAttrs.value) {
      uploadValue = bindAttrs.value;
    }
    data[prop] = files.map((f) => f[uploadValue]).join(',');

    if (bindAttrs) {
      Object.keys(bindAttrs).map((attr) => {
        if (attr && attr !== 'value') {
          const values = files.map((f) => f[attr]);
          data[bindAttrs[attr]] = values.join(',');
        }
      });
    }
  }
};

export const transSingleCheckboxVal = (data, e) => {
  const { type, prop, bindLabel, content, trueValue } = e;
  if (type == 'singleCheckbox' && data[prop] == trueValue && bindLabel) {
    data[bindLabel] = content;
  }
};

export const transRadioVal = (data, e) => {
  const { type, prop, bindLabel } = e;
  if (type == 'radio' && data[prop] && data[`$${prop}`] && bindLabel) {
    data[bindLabel] = data[`$${prop}`];
  }
};

// 复选框组需要把对应值数组转换为逗号分隔的字符串
export const transCheckboxVal = (data, e) => {
  const { type, prop, bindLabel } = e;
  if (type == 'checkbox' && data[prop] && data[prop].length) {
    data[prop] = data[prop].join(',');

    if (bindLabel && data[`$${prop}`]) {
      data[bindLabel] = data[`$${prop}`].replaceAll('|', ',').replaceAll(' ', '');
    }
  }
};

export const transSwitchVal = (data, e) => {
  const { type, prop, bindLabel, dicData } = e;
  if (type == 'switch' && bindLabel && data[prop]) {
    data[bindLabel] = dicData.find((item) => item.value == data[prop]).label;
  }
};

export const transUserTypeVal = (data, e) => {
  const { type, prop, bindLabel } = e;
  if (type == 'userType' && data[prop]) {
    const dataClone = data[prop];
    data[prop] = dataClone.value;
    if (bindLabel) {
      data[bindLabel] = dataClone.label;
    }
  }
};

// 级联数组模式下需要转化为逗号分隔的字符串
export const transCascaderVal = (data, e) => {
  const { type, prop, cascaderProps } = e;
  if (type == 'anvilCascader' && data[prop] && cascaderProps && (cascaderProps.emitPath || cascaderProps.multiple)) {
    data[prop] = data[prop].join(',');
  }
};

// 对携带bindAttrs参数的组件的值进行转换,根据值类型是对象或数组处理结果不同
export const tansBindAttrsVal = (data, e) => {
  const { type, bindAttrs, prop } = e;
  if (type !== 'upload' && bindAttrs && data[prop]) {
    const dataClone = cloneDeep(data[prop]);

    Object.keys(bindAttrs).map((attr) => {
      // 处理对象值类型
      if (Object.prototype.toString.call(dataClone) == '[object Object]') {
        if (attr == 'value') {
          data[prop] = dataClone[bindAttrs.value];
        } else if (attr) {
          const value = dataClone[e[attr] ? e[attr] : attr];
          data[bindAttrs[attr]] = value;
        }
      }
      // 处理数组值类型
      else if (Object.prototype.toString.call(dataClone) == '[object Array]') {
        if (attr == 'value') {
          data[prop] = dataClone.map((item) => item[bindAttrs.value]).join(',');
        } else if (attr) {
          const values = dataClone.map((item) => item[e[attr] ? e[attr] : attr]);
          data[bindAttrs[attr]] = values.join(',');
        }
      }
    });
  }
};

// 子表单组件值变化时，对内部特定组件的字段值进行处理后传递出去
const transDynamicVal = (data, e) => {
  const { type, prop, children } = e;
  if (type == 'anvilDynamic' && data[prop]) {
    const list = data[prop];
    list.map((itemData) => {
      children.column.map((col) => {
        handleValueTrans(itemData, col);
      });
    });
  }
};

export const transBackSelectVal = (data, e) => {
  const { type, multiple, prop } = e;
  if (type == 'select' && multiple && data[prop] && typeof data[prop] == 'string') {
    data[prop] = data[prop].split(',');
  }
};

export const transBackCheckboxVal = (data, e) => {
  const { type, bindLabel, prop } = e;
  if (type == 'checkbox' && data[prop] && typeof data[prop] == 'string') {
    data[prop] = data[prop].split(',');
  }
};

// 处理输入框接收组件值时，强制转为string类型
const transBackInputVal = (data, e) => {
  const { type, prop } = e;
  if ((type == 'input' || type == 'textarea') && !isEmpty(data[prop]) && typeof data[prop] !== 'string') {
    data[prop] = String(data[prop]);
  }
};

// 处理数字输入框接收组件值时，强制转为number类型
const transBackNumberVal = (data, e) => {
  const { type, prop } = e;
  if (type == 'number' && !isEmpty(data[prop]) && typeof data[prop] !== 'number') {
    data[prop] = Number(data[prop]);
  }
};

// 附件回填时需要拼接多个字段组合成文件对象
export const transBackUploadVal = (data, e) => {
  const { type, prop, bindAttrs, listType } = e;
  if (type == 'upload' && data[prop] && typeof data[prop] == 'string') {
    const uploadFiles = [];
    // 长度等于文件个数
    const len = data[prop].split(',').length;
    for (let i = 0; i < len; i++) {
      const fileObj = {};
      let uploadValue = 'fileId';
      // 默认属性设置
      if (bindAttrs && bindAttrs.value) {
        uploadValue = bindAttrs.value;
      }
      fileObj[uploadValue] = data[prop].split(',')[i];
      if (uploadValue == 'fileId') {
        fileObj.url = generateFileUrlByFileId(fileObj[uploadValue]);
      } else {
        fileObj.url = generateFileUrl(fileObj[uploadValue]);
      }
      fileObj.type = listType && listType.includes('picture') ? 'img' : 'file'; // 根据上传类型添加不同默认类型
      fileObj.fileName = '附件';

      if (bindAttrs) {
        Object.keys(bindAttrs).map((attr) => {
          if (attr && attr !== 'value' && data[bindAttrs[attr]]) {
            const values = String(data[bindAttrs[attr]]).split(',');
            fileObj[attr] = values[i];
          }
        });
      }

      uploadFiles.push(fileObj);
    }
    data[prop] = uploadFiles;
  }
};

export const transBackUserTypeVal = (data, e) => {
  const { type, prop, bindLabel } = e;
  if (type == 'userType' && data[prop]) {
    let obj = {
      label: '',
      value: ''
    };
    obj.value = data[prop];
    if (bindLabel && data[bindLabel]) {
      obj.label = data[bindLabel];
    }
  }
};

export const transBackImgViewerVal = (data, e) => {
  const { type, prop, bindImgList } = e;
  if (type == 'imgViewer' && bindImgList && data[bindImgList] && typeof data[bindImgList] == 'string') {
    data[bindImgList] = data[bindImgList].split(',');
  }
};

// 级联数组模式下从字符串解析为数组
export const transBackCascaderVal = (data, e) => {
  const { type, prop, cascaderProps } = e;
  if (type == 'anvilCascader' && data[prop] && typeof data[prop] == 'string' && cascaderProps && (cascaderProps.emitPath || cascaderProps.multiple)) {
    data[prop] = data[prop].split(',');
  }
};

export const transBackBindAttrsVal = (data, e) => {
  const { type, prop, bindAttrs, valueType } = e;
  if (type !== 'upload' && bindAttrs && data[prop]) {
    if (typeof data[prop] !== 'string') {
      data[prop] = String(data[prop]);
    }
    // 现在默认设置了bindAttrs属性的组件数据类型只有对象与数组
    if (valueType == 'array') {
      const res = [];
      // 长度等于对象个数
      const len = data[prop].split(',').length;
      for (let i = 0; i < len; i++) {
        const obj = {};

        Object.keys(bindAttrs).map((attr) => {
          if (attr == 'value') {
            // bindAttr中value对应值就是表单值中对应的属性
            obj[bindAttrs.value] = data[prop].split(',')[i];
          } else if (attr && data[bindAttrs[attr]]) {
            const values = String(data[bindAttrs[attr]]).split(',');
            obj[attr] = values[i];
          }
        });

        res.push(obj);
      }
      data[prop] = res;
    } else {
      const obj = {};
      Object.keys(bindAttrs).map((attr) => {
        if (attr == 'value') {
          // bindAttr中value对应值就是表单值中对应的属性
          obj[bindAttrs.value] = data[prop];
        } else if (attr && data[bindAttrs[attr]]) {
          const value = data[bindAttrs[attr]];
          obj[e[attr] ? e[attr] : attr] = value;
        }
      });
      data[prop] = obj;
    }
  }
};

const transBackDynamicVal = (data, e) => {
  const { type, prop, children } = e;
  if (type == 'anvilDynamic' && data[prop]) {
    const list = data[prop];
    list.map((itemData) => {
      children.column.map((col) => {
        handleValueTransBack(itemData, col);
      });
    });
  }
};

export const handleValueTrans = (data, e) => {
  appendDateRangeStartEnd(data, e);
  transSelectVal(data, e);
  transUploadVal(data, e);
  transSingleCheckboxVal(data, e);
  transCheckboxVal(data, e);
  transRadioVal(data, e);
  transSwitchVal(data, e);
  transUserTypeVal(data, e);
  tansBindAttrsVal(data, e);
  transCascaderVal(data, e);
  transDynamicVal(data, e);
};

export const handleValueTransBack = (data, e) => {
  appendDateRangeStartEndBack(data, e);
  transBackInputVal(data, e);
  transBackNumberVal(data, e);
  transBackSelectVal(data, e);
  transBackUploadVal(data, e);
  transBackCheckboxVal(data, e);
  transBackUserTypeVal(data, e);
  transBackBindAttrsVal(data, e);
  transBackCascaderVal(data, e);
  transBackDynamicVal(data, e);
};
